package com.example.li_han.servlet;

import com.example.li_han.service.UserService;
import com.example.li_han.pojo.User;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//获取所有的普通用户信息

@WebServlet(name = "GetAllUsersServlet", value = "/GetAllUsersServlet")

public class GetAllUsersServlet extends HttpServlet {
    private Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("UTF-8");

        Map<String, Object> resultMap = new HashMap<>();

        try {
            UserService userService = new UserService();
            List<User> users = userService.getAllUsers();

            resultMap.put("code", 200);
            resultMap.put("msg", "获取用户列表成功");
            resultMap.put("data", users);
            resultMap.put("count", users.size());

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "获取用户列表失败: " + e.getMessage());
        }

        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}
